﻿using AutoMapper;
using MediatR;
using SU.Center.Domain.RBAC;
using SU.Center.Infa;
using System.Transactions;

namespace SU.Center.Api.Handler.RBAC
{
    /// <summary>
    /// 新增角色权限
    /// </summary>
    public class InserRolePermissionHandler : IRequestHandler<InserRolePermissionReqsultDto, ApiResult>
    {
        private readonly IBaseReposiotry<Roles> baseReposiotry;
        private readonly IBaseReposiotry<RolePermissions> reposiotry;
        private readonly IMapper mapper;
        private readonly ILogger<InserRolePermissionHandler> logger;

        public InserRolePermissionHandler(IBaseReposiotry<Roles> baseReposiotry, IBaseReposiotry<RolePermissions> reposiotry, IMapper mapper, ILogger<InserRolePermissionHandler> logger)
        {
            this.baseReposiotry = baseReposiotry;
            this.reposiotry = reposiotry;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(InserRolePermissionReqsultDto request, CancellationToken cancellationToken)
        {
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var role = mapper.Map<Roles>(request);
                    await baseReposiotry.InsetAsync(role);

                    string[] strings = request.PermissionIds.Split(',');
                    int[] intIds = strings.Select(x => int.Parse(x)).ToArray();
                    var list = new List<RolePermissions>();

                    foreach (var id in intIds)
                    {
                        list.Add(new RolePermissions() { RoleId = role.RolesId, PermissionId = id });
                    }

                    await reposiotry.InsertRangeEntity(list);
                    tran.Complete();
                    return ApiResult.Ok();
                }
                finally
                {
                    tran.Dispose();
                }
            }
        }
    }

    public class InserRolePermissionReqsultDto : IRequest<ApiResult>
    {
        public string RoleName { get; set; }
        public string PermissionIds { get; set; }
    }
}
